<template>
  <div class="product-container">
    <div class="product-row">
      <div class="row-item image-description-container">
        <img :src="imageUrls(products[0].filename)" alt="Product Image" v-if="products.length > 0 && imageUrls(products[0].filename)" />
        <p v-else>未找到对应的图片</p>
        <p class="description-text" v-if="products.length > 0">{{ products[0].description }}</p>
      </div>
      <div class="row-item" v-if="products.length > 0">
        <strong>{{ products[0].id }}</strong>
      </div>
      <div class="row-item" v-if="products.length > 0">
        <strong style="font-size: 1.2rem;">{{ products[0].attribute }}</strong>
      </div>
      <div class="row-item">
        {{ name }}
      </div>
      <div class="row-item" v-if="products.length > 0">
         {{ products[0].inventory }} in stock
      </div>
      <div class="row-item" v-if="products.length > 0">
        {{ '$' + products[0].price }}
      </div>
      <div class="row-item">
        <el-button type="primary" size="large" class="add-cart" @click="handleAddToCart">add to cart</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import router from '../router';
import { ElMessage } from 'element-plus'

// 定义图片URL映射
const imageUrls = (filename) => {
  return require(`@/assets/${filename}`);
};

// 假设这是从外部传入的productId
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import apiClient from '@/api/api'
import store from '@/store'

const route = useRoute()
const productId = computed(() => route.params.productId)
const name = computed(() => route.params.name)
const loading = ref(false)
const cateId = ref('')
// 产品数据
const products = ref([])
// 用户是否登录
const isLoggedIn = ref(store.getters.getLoginStatus)
// 弹出层
const drawer = ref(false)
// 添加购物车的数量
const quantity = ref(1)
// 关闭弹出层
const handleClose = (done) => {
  quantity.value = 1
  productId.value = ''
  done()
}
// 显示弹出层
const showDrawer = (id) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('please login first')
    return
  }
  drawer.value = true
  productId.value = id
}
// 加入购物车数量变化
const handleQuantityChange = (value) => {
  quantity.value = value
}
const handleAddToCart = async () => {
  // 发送请求到后端，将商品添加到购物车
  apiClient.post(`/carts?itemId=${productId.value}&&quantity=${quantity.value}`)
    .then((response) => {
      if (response.data.status === 0) {
        ElMessage({
          message: 'Added to cart successfully',
          type: 'success'
        })
      } else {
        ElMessage({
          message: response.data.message,
          type: 'error'
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: error.message,
        type: 'error'
      })
    })
}
const loadCategoriesData = async () => {
  try {
    const response = await apiClient.get(`/items/${productId.value}`);
    const response2 = await apiClient.get(`/desc/${response.data.data.itemId}`);
    const response3 = await apiClient.get(`/inventory/${response.data.data.itemId}`);
    if (response.data.status === 0) {
      products.value.push({
        id: response.data.data.itemId,
        attribute: response.data.data.attribute1,
        price: response.data.data.listPrice,
        filename: response2.data.data.fileName,
        description: response2.data.data.description,
        inventory: response3.data.data.quantity,
      });

    } else {
      ElMessage({
        message: response.data.message,
        type: 'error'
      });
    }

  } catch (error) {
    ElMessage({
      message: '请求失败，请检查网络连接',
      type: 'error'
    });
    console.error('Full error:', error);
  }
}
import { onMounted } from 'vue';
onMounted(async () => {
  try {
    await loadCategoriesData();
    console.log(products.value);
    console.log(imageUrls(products.value[0].filename));
  } catch (error) {
    ElMessage.error('Error loading data');
  }
})

</script>

<style scoped>
.product-container {
  background-color: #f5f5f5;
  padding: 50px;
  text-align: left;
}

.product-row {
  display: flex;
  flex-direction: column;
}

.image-description-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.description-text {
  max-width: 300px;
}

.row-item {
  padding: 10px 0;
  border-bottom: 1px solid #fff;
}

.el-table {
  border: none;
}
</style>